import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { getToken } from 'utils'
import { message } from 'antd'
import { history } from 'utils'
//创建请求实例
const instance = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
  timeout: process.env.TIME_OUT as unknown as number,
})

//请求拦截器
instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = getToken()
    if (token && config.url !== '/captchaImage' && config.url !== '/login') { // 这个条件没复用性, 用来解决后端接口bug的
      config.headers!.Authorization = 'Bearer ' + token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

//响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const code = response.data?.code
    if (code === 401) { //token过期
      history.push('/login')
      message.error('身份认证过期, 请重新登陆!')
      return Promise.reject(new Error(response.data.msg))
    }
    console.log(code);
    if (code === 500) { // 手机重复
      return Promise.reject(response.data.msg)
    }

    return response.data
  },
  (error) => {
    return Promise.reject(error)
  }
)

//创建请求接口
export const createApi = (url: string, method: string, data?: object) => {
  const config: any = {}
  if (method === 'GET') {
    config.params = data
  } else {
    config.data = data
  }
  return instance({
    url,
    method,
    ...config,
  })
}

//图片上传请求
// export const createFormAPI = (url, method, data) => {
//   const config = {}
//   config.data = data
//   config.headers = {
//     'Cache-Control': 'no-cache',
//     'Content-Type': 'application/x-www-form-urlencoded',
//   }
//   config.responseType = 'json'
//   config.transformRequest = [
//     function (data) {
//       let ret = ''
//       for (const it in data) {
//         ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
//       }
//       return ret
//     },
//   ]
//   return instance({
//     url,
//     method,
//     ...config,
//   })
// }
